package com.tulingxueyuan.mall.modules.pms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tulingxueyuan.mall.dto.ProductConditionDTO;
import com.tulingxueyuan.mall.dto.ProductSaveParamsDTO;
import com.tulingxueyuan.mall.dto.ProductUpdateInitDTO;
import com.tulingxueyuan.mall.modules.pms.model.PmsProduct;
import com.tulingxueyuan.mall.modules.pms.mapper.PmsProductMapper;
import com.tulingxueyuan.mall.modules.pms.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author Miao
 * @since 2022-05-19
 */
@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {

    @Resource
    PmsProductMapper pmsProductMapper;
    @Resource
    PmsMemberPriceService pmsMemberPriceService;
    @Resource
    PmsProductLadderService pmsProductLadderService;
    @Resource
    PmsProductFullReductionService pmsProductFullReductionService;
    @Resource
    PmsProductAttributeValueService productAttributeValueService;
    @Resource
    PmsSkuStockService pmsSkuStockService;
    @Resource
    PmsProductAttributeValueService pmsProductAttributeValueService;

    /**
     * 商品列表
     * @param productConditionDTO
     * @return
     */
    @Override
    public Page list(ProductConditionDTO productConditionDTO) {
        Page page=new Page<>(productConditionDTO.getPageNum(),productConditionDTO.getPageSize());
        QueryWrapper<PmsProduct> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<PmsProduct> lambdaQueryWrapper=queryWrapper.lambda();
        // 商品名称
        if(!StrUtil.isBlank(productConditionDTO.getKeyword())){
            lambdaQueryWrapper.like(PmsProduct::getName,productConditionDTO.getKeyword());
        }
        // 商品货号
        if(!StrUtil.isBlank(productConditionDTO.getProductSn())){
            lambdaQueryWrapper.eq(PmsProduct::getProductSn,productConditionDTO.getProductSn());
        }
        // 商品分类
        if(productConditionDTO.getProductCategoryId()!=null && productConditionDTO.getProductCategoryId()>0){
            lambdaQueryWrapper.eq(PmsProduct::getProductCategoryId,productConditionDTO.getProductCategoryId());
        }
        // 商品品牌
        if(productConditionDTO.getBrandId()!=null && productConditionDTO.getBrandId()>0){
            lambdaQueryWrapper.eq(PmsProduct::getBrandId,productConditionDTO.getBrandId());
        }
        // 上架状态
        if(productConditionDTO.getPublishStatus()!=null){
            lambdaQueryWrapper.eq(PmsProduct::getPublishStatus,productConditionDTO.getPublishStatus());
        }
        // 审核状态
        if(productConditionDTO.getVerifyStatus()!=null){
            lambdaQueryWrapper.eq(PmsProduct::getVerifyStatus,productConditionDTO.getVerifyStatus());
        }
        lambdaQueryWrapper.orderByAsc(PmsProduct::getSort);
        return this.page(page,lambdaQueryWrapper);
    }

    /**
     * 上架状态、新品状态、推荐状态更新
     * @param status
     * @param ids
     * @param getPublicStatus
     * @return
     */
    @Override
    public boolean updateStatus(Integer status, List<Long> ids, SFunction<PmsProduct, ?> getPublicStatus) {
        UpdateWrapper<PmsProduct> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().set(getPublicStatus,status).in(PmsProduct::getId,ids);
        return this.update(updateWrapper);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public ProductUpdateInitDTO getUpdateInfo(Long id) {
        return pmsProductMapper.getUpdateInfo(id);
    }

    /**
     * 更新商品信息
     * @param productSaveParamsDTO
     * @return
     */
    @Override
    @Transactional
    public boolean update(ProductSaveParamsDTO productSaveParamsDTO) {
        // 1.保存商品基本信息——商品表
        PmsProduct pmsProduct=productSaveParamsDTO;
        boolean result=this.updateById(pmsProduct);
        // 2.保存成功后保存——SKU和SPU表
        if(result){
            // 促销方式
            switch (pmsProduct.getPromotionType()){
                case 2:
                    // 会员价格
                    // 根据商品id删除
                    DeleteManyListByProductId(pmsProduct.getId(),pmsMemberPriceService);
                    SaveManyList(productSaveParamsDTO.getMemberPriceList(),pmsProduct.getId(),pmsMemberPriceService);
                    break;
                case 3:
                    // 根据商品id删除
                    // 阶梯价格
                    DeleteManyListByProductId(pmsProduct.getId(),pmsProductLadderService);
                    SaveManyList(productSaveParamsDTO.getProductLadderList(),pmsProduct.getId(),pmsProductLadderService);
                    break;
                case 4:
                    // 根据商品id删除
                    // 满减价格
                    DeleteManyListByProductId(pmsProduct.getId(),productAttributeValueService);
                    SaveManyList(productSaveParamsDTO.getProductFullReductionList(),pmsProduct.getId(),pmsProductFullReductionService);
                    break;
            }
            // sku根据商品id删除
            DeleteManyListByProductId(pmsProduct.getId(),pmsSkuStockService);
            SaveManyList(productSaveParamsDTO.getSkuStockList(),pmsProduct.getId(),pmsSkuStockService);
            // spu根据商品id删除
            DeleteManyListByProductId(pmsProduct.getId(),pmsProductAttributeValueService);
            SaveManyList(productSaveParamsDTO.getProductAttributeValueList(),pmsProduct.getId(),productAttributeValueService);
        }
        return result;
    }

    /**
     *
     * @param ids
     * @param deleteStatus
     * @return
     */
    @Override
    public boolean deleteStatus(List<Long> ids, Integer deleteStatus) {
        UpdateWrapper<PmsProduct> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(PmsProduct::getDeleteStatus,deleteStatus)
                .in(PmsProduct::getId,ids);
        boolean result=this.update(updateWrapper);
        for (Long id:ids){
            PmsProduct pmsProduct=this.getById(id);
            System.out.println(pmsProduct.getDeleteStatus());
        }
        return result;
    }

    /**
     * 添加
     * @param productSaveParamsDTO
     * @return
     */
    @Override
    public boolean create(ProductSaveParamsDTO productSaveParamsDTO) {
        PmsProduct pmsProduct=productSaveParamsDTO;
        pmsProduct.setId(null);
        boolean result=this.save(pmsProduct);
        if(result){
            switch (pmsProduct.getPromotionType()){
                case 2:
                    SaveManyList(productSaveParamsDTO.getMemberPriceList(),pmsProduct.getId(),pmsMemberPriceService);
                    break;
                case 3:
                    SaveManyList(productSaveParamsDTO.getProductLadderList(),pmsProduct.getId(),pmsProductLadderService);
                    break;
                case 4:
                    SaveManyList(productSaveParamsDTO.getProductFullReductionList(),pmsProduct.getId(),pmsProductFullReductionService);
                    break;
            }
            SaveManyList(productSaveParamsDTO.getSkuStockList(),pmsProduct.getId(),pmsSkuStockService);
            SaveManyList(productSaveParamsDTO.getProductAttributeValueList(),pmsProduct.getId(),pmsProductAttributeValueService);
        }
        return result;
    }

    /**
     * 根据商品id删除关联数据
     * @param productId
     * @param service
     */
    public void DeleteManyListByProductId(Long productId, IService service){
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("product_id",productId);
        service.remove(queryWrapper);
    }

    /**
     * 公共方法： 保存会员价格、阶梯价格、减满价格、 sku 、 spu 商品的关联数据
     * @param list
     * @param productId
     * @param service
     */
    public void SaveManyList(List list,Long productId,IService service){
        if(CollectionUtil.isEmpty(list)) return;
        try{
            // 循环 反射 赋值商品id
            for(Object obj:list){
                // 在修改状态清除主键id
                Method setProductIdMethod=obj.getClass().getMethod("setProductId",Long.class);
                Method setId=obj.getClass().getMethod("setId",Long.class);
                // 调用Method类代表的方法
                setId.invoke(obj,(Long)null);
                setProductIdMethod.invoke(obj,productId);
            }
            service.saveBatch(list);
        }
        catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }

}
